import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const location = useLocation();
  
  // 检查是否已认证
  const isAuthenticated = () => {
    const token = localStorage.getItem('auth_token');
    const authTime = localStorage.getItem('auth_time');
    
    if (!token || !authTime) {
      return false;
    }
    
    // 检查token是否过期（可选：设置24小时过期）
    const now = Date.now();
    const time = parseInt(authTime, 10);
    const maxAge = 24 * 60 * 60 * 1000; // 24小时
    
    if (now - time > maxAge) {
      // Token过期，清除认证信息
      localStorage.removeItem('auth_token');
      localStorage.removeItem('auth_time');
      return false;
    }
    
    return true;
  };

  if (!isAuthenticated()) {
    // 保存当前路径，以便登录后重定向回来
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return <>{children}</>;
};

export default ProtectedRoute;

